//
//  BDQuanMinHomeViewController.m
//  BeidouMall
//
//  Created by qie on 16/8/2.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDQuanMinHomeViewController.h"
#import "BDQuanMinHomeHeaderView.h"
#import "BDGoodDetailViewController.h"
#import "BDNavigationController.h"
#import "BDBeidouPayViewController.h"

#define kPageSize 5

@interface BDQuanMinHomeViewController () < UITableViewDelegate,
                                            UITableViewDataSource,
                                            BDQuanMinHomeHeaderViewDelegate,
                                            SimplePopupViewDelegate >
{
    NSInteger _curPage;
    NSMutableArray *_dataList;
    
    BDQuanMinHomeHeaderView *_quanminiHeaderView;
    UIImageView *_navBarHairlineImageView;// 原生导航栏上的黑线
    SimplePopupView *_popView;
    
    NSIndexPath *_selectedIndexPath;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleImageHeight;

@property (weak, nonatomic) IBOutlet UIView *buyPopView;
@property (weak, nonatomic) IBOutlet UIView *buySurfaceView;


@end

@implementation BDQuanMinHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 处理tableView上面多出来20个像素(是因为自动布局的缘故)
    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 自定义tableview刷新的头部和尾部
    [self setTableViewHeader];
    [self setTableViewFooter];
    _dataList = [[NSMutableArray alloc] init];
    [_tableView.mj_header beginRefreshing];
    _curPage = 0;
    
    [self setHeaderPopView];
    
    if (kScreen_Width <= 320.0) {// iphone5
        self.titleImageHeight.constant = 110;
    } else if (kScreen_Width > 320.0 && kScreen_Width <= 375.0) { // iphone6
        self.titleImageHeight.constant = 128;
    } else if (kScreen_Width > 375.0) { //iphone6p
        self.titleImageHeight.constant = 138;
    }
    
    self.title = @"优惠券";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self hideNavgationBarBlackLine];
    // nav_bg2一个透明的图片替换原来的nav_bg
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg2"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES;
    _quanminiHeaderView = [[NSBundle mainBundle] loadNibNamed:@"BDQuanMinHomeHeaderView" owner:nil options:nil].firstObject;
    _quanminiHeaderView.frame = CGRectMake(0.0, 0.0, kScreen_Width, 64.0);
    _quanminiHeaderView.tag = 941;
    _quanminiHeaderView.delegate = self;
    [self.navigationController.view addSubview:_quanminiHeaderView];
    
    [self dropShadowWithOffset:CGSizeMake(0, 0)
                        radius:2
                         color:[UIColor lightGrayColor]
                       opacity:0.8];
    
    _buyPopView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _navBarHairlineImageView.hidden = NO;
    
    if (_quanminiHeaderView) {
        [_quanminiHeaderView removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private method

- (void)reloadData:(id) sender {
    _curPage = sender == self ? 1 : _curPage + 1;
    if (_curPage == 1) {// 消除没有更多数据的状态
        [_tableView.mj_footer resetNoMoreData];
    }
    
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString *nowDateStr = [dateformatter stringFromDate:nowDate];
    
    NSString *url;
    if ([BDAccountManagerModel shareInstance].isLogin) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&date=%@&userId=%@",
               [BDNetworking shareInstance].baseUrl,
               Kanjia_Query,
               (long)_curPage,
               kPageSize,
               nowDateStr,
               [BDAccountManagerModel shareInstance].userId];
    } else {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&date=%@",
               [BDNetworking shareInstance].baseUrl,
               Kanjia_Query,
               (long)_curPage,
               kPageSize,
               nowDateStr];
    }
    
    MBProgressHUD *hud;
    
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_header isRefreshing]) {
                [_tableView.mj_header endRefreshing];
            }
            if ([_tableView.mj_footer isRefreshing]) {
                [_tableView.mj_footer endRefreshing];
            }
        });
        if (error != nil) {
            NSLog(@"砍价商品获取失败:%@",error);
            if (hud) {
                hud.labelText = @"砍价商品获取失败";
                [hud hideAfterDelay:0.5];
            } else {
                [MBProgressHUD showToast:self.view withText:@"砍价商品获取失败"];
            }
        } else {
            if (hud) {
                [hud hideAfterDelay:0.5];
            }
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSLog(@"results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                if ([resultList count] > 0) {
                    if ([resultList count] < kPageSize) {// 数据不够分页,显示没有更多了
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
                    if (sender == self) {
                        [_dataList removeAllObjects];
                    }
                    [_dataList addObjectsFromArray:resultList];
                } else {
                    if (_curPage > 1) { // 分页引起的刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    } else { // 刷新之前的数据应该清零
                        [_dataList removeAllObjects];
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_tableView reloadData];
                });
            }
        }
    }];
}

- (void)setTableViewHeader {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData:self];
    }];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        header.stateLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    
    [header setTitle:NSLocalizedString(@"Pull down to refresh", nil) forState:MJRefreshStateIdle];
    [header setTitle:NSLocalizedString(@"Release to refresh", nil) forState:MJRefreshStatePulling];
    [header setTitle:NSLocalizedString(@"Loading ...", nil) forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    _tableView.mj_header = header;
}

- (void)setTableViewFooter {
    _tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadData:)];
}

- (void)hideNavgationBarBlackLine {
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        _navBarHairlineImageView = imageView2;
                        _navBarHairlineImageView.hidden = YES;
                    }
                }
            }
        }
    }
}

- (void)setHeaderPopView {
    NSArray *tmpArray = @[NSLocalizedString(@"home", nil),NSLocalizedString(@"message", nil)];
    NSArray *images = @[@"homeback",@"messageback"];
    //左
    _popView = [[SimplePopupView alloc] initWithFrame:CGRectMake(kScreen_Width - 130.0, 55.0, 120.0, 80.0)
                                         andDirection:PopViewDirectionTop
                                            andTitles:tmpArray
                                            andImages:images
                                       trianglePecent:0.5]; //箭头位于popview中间0.5位置
    [self.navigationController.navigationBar showPopView:_popView AtPoint:CGPointMake(0.5, 0)];//箭头位于button的x=0.y=0.5比例处
    _popView.delegate = self; //需要正式使用时注意代理
}

- (void)dropShadowWithOffset:(CGSize)offset
                      radius:(CGFloat)radius
                       color:(UIColor *)color
                     opacity:(CGFloat)opacity {
    
    // Creating shadow path for better performance
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, _buySurfaceView.bounds);
    _buySurfaceView.layer.shadowPath = path;
    CGPathCloseSubpath(path);
    CGPathRelease(path);
    
    _buySurfaceView.layer.shadowColor = color.CGColor;
    _buySurfaceView.layer.shadowOffset = offset;
    _buySurfaceView.layer.shadowRadius = radius;
    _buySurfaceView.layer.shadowOpacity = opacity;
    
    // Default clipsToBounds is YES, will clip off the shadow, so we disable it.
    _buySurfaceView.clipsToBounds = NO;
    
}

#pragma mark tableView dataSrouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataList.count > 0 ? _dataList.count : 1 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_dataList.count > 0) {
        static NSString *cellStr = @"searchCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        // 商品图片
        NSString *goodImageUrl = _dataList[indexPath.row][@"commodity"][@"icon"];
        UIImageView *goodImageView = (UIImageView *)[cell viewWithTag:101];
        if (![goodImageUrl isEqual:[NSNull null]]) {
            [goodImageView sd_setImageWithURL:[NSURL URLWithString:goodImageUrl] placeholderImage:[UIImage imageNamed:@"image_empty"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                if (image.size.width / image.size.height >= 1.1) {// banner商品(宽:高) 1.8:1 显示
                    for (NSLayoutConstraint* constraint in goodImageView.constraints) {
                        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                            constraint.constant = 95.0 / (image.size.width / image.size.height);
                        }
                    }
                    for (NSLayoutConstraint* constraint in cell.contentView.constraints) {
                        if ([constraint.identifier isEqualToString:@"imageLeading"]) {
                            constraint.constant = 8;
                        }
                    }
                } else if (image.size.width / image.size.height <= 0.9) {
                    for (NSLayoutConstraint* constraint in goodImageView.constraints) {
                        if (constraint.firstAttribute == NSLayoutAttributeWidth) {
                            constraint.constant = 92.0 * (image.size.width / image.size.height);
                        }
                    }
                    for (NSLayoutConstraint* constraint in cell.contentView.constraints) {
                        if ([constraint.identifier isEqualToString:@"imageLeading"]) {
                            CGFloat minus =  92.0 - 92.0 * (image.size.width / image.size.height);
                            constraint.constant = 8 + minus / 2;
                        }
                    }
                } else {
                    for (NSLayoutConstraint* constraint in goodImageView.constraints) {// NSLayoutAttributeLeading
                        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
                            constraint.constant = 95.0;
                        }
                        if (constraint.firstAttribute == NSLayoutAttributeWidth) {
                            constraint.constant = 92.0;
                        }
                    }
                    for (NSLayoutConstraint* constraint in cell.contentView.constraints) {
                        if ([constraint.identifier isEqualToString:@"imageLeading"]) {
                            constraint.constant = 8;
                        }
                    }
                }
            }];
        }
        // 商品名称
        UILabel *goodNameLabel = (UILabel *)[cell viewWithTag:102];
        NSString *goodName = _dataList[indexPath.row][@"commodity"][@"name"];
        if (![goodName isEqual:[NSNull null]]) {
            goodNameLabel.text = goodName;
        }
        // 商品描述
        UILabel *goodDescLabel = (UILabel *)[cell viewWithTag:103];
        NSString *goodDesc = _dataList[indexPath.row][@"commodity"][@"address"];
        if (![goodDesc isEqual:[NSNull null]]) {
            goodDescLabel.text = [NSString stringWithFormat:@"产地：%@",goodDesc];
        }
        // 商品库存
        UILabel *goodNumLabel = (UILabel *)[cell viewWithTag:104];
        NSString *goodNum = _dataList[indexPath.row][@"commodity"][@"num"];
        if (![goodNum isEqual:[NSNull null]]) {
            goodNumLabel.text = [NSString stringWithFormat:@"库存：%@",goodNum];
        }
        // 商品当前价格
        UILabel *goodDiscountLabel = (UILabel *)[cell viewWithTag:106];
        // 商品原价格
        UILabel *goodPriceLabel = (UILabel *)[cell viewWithTag:107];
        
        NSString *goodDiscount = _dataList[indexPath.row][@"currentPrice"];
        NSString *goodPrice = _dataList[indexPath.row][@"price"];
        if (![goodDiscount isEqual:[NSNull null]] &&
            ![goodPrice isEqual:[NSNull null]]) {
            // 折扣价格
            goodDiscountLabel.text = [NSString stringWithFormat:@"当前价格:¥ %.2f",[goodDiscount floatValue]];
            // 价格
            NSString *str = [NSString stringWithFormat:@"原价:¥ %.2f",[goodPrice floatValue]];
            
            NSMutableAttributedString * attribtStr = [[NSMutableAttributedString alloc] initWithString:str];
            [attribtStr addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(3, attribtStr.length - 3)];
            goodPriceLabel.attributedText = attribtStr;
        }
        // 购买按钮
        UIButton *buyButton = (UIButton *)[cell viewWithTag:108];
        if (![goodNum isEqual:[NSNull null]] && [goodNum integerValue] > 0) {
            buyButton.titleLabel.textColor = RGBColor(215, 19, 33);
            buyButton.layer.borderColor = RGBColor(215, 19, 33).CGColor;
            buyButton.layer.borderWidth = 1.0;
            buyButton.enabled = YES;
        } else {// 商品数量小于0
            buyButton.titleLabel.textColor = RGBColor(153, 153, 153);
            buyButton.layer.borderColor = RGBColor(153, 153, 153).CGColor;
            buyButton.layer.borderWidth = 1.0;
            buyButton.enabled = NO;
        }
        
        
        
        return cell;
    } else {
        static NSString *cellStr = @"noCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        return cell;
    }
    
}

#pragma mark tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    _tableView.scrollEnabled = _dataList.count > 0 ? YES : NO;
    return _dataList.count > 0 ? 110.0 : kScreen_Height - 104.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataList.count > 0) {
        NSString *commodityId = _dataList[indexPath.row][@"commodity"][@"commodityId"];
        if ([commodityId isEqual:[NSNull null]] ||
            commodityId != nil) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

#pragma mark BDQuanMinHomeHeaderViewDelegate

- (void)backMethod {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)homeMethod:(UIButton *)sender {
    [_popView show];
}

- (void)simplePopupView:(SimplePopupView *)popView clickAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"代理方法，点击了第%ld行",(long)indexPath.row);
    if (indexPath.row == 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    } else if (indexPath.row == 1) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Still in process", nil)];
    }
}

#pragma mark - IBActions

- (IBAction)buyButtonPressed:(UIButton *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    _selectedIndexPath = indexPath;
    
    NSDictionary *record = (NSDictionary *)_dataList[indexPath.row][@"record"];
    if ([record isEqual:[NSNull null]]) {
        _buyPopView.hidden = NO;
    } else {
        BOOL flag = NO;
        // 是否是便民商品
        NSDictionary *classify = _dataList[indexPath.row][@"commodity"][@"classify"];
        if (![classify isEqual:[NSNull null]] &&
            [classify isKindOfClass:[NSDictionary class]]) {
            NSString *firstLevel = classify[@"firstLevel"];
            if (![firstLevel isEqual:[NSNull null]]) {
                if ([firstLevel isEqualToString:@"conveniency"]) {
                    flag = YES;
                }
            }
        }
        
        NSString *storeName = _dataList[indexPath.row][@"commodity"][@"store"][@"name"];
        if ([storeName isEqual:[NSNull null]]) {
            storeName = @"某店铺";
        }
        NSString *storeId = _dataList[indexPath.row][@"commodity"][@"store"][@"storeId"];
        if ([storeId isEqual:[NSNull null]]) {
            storeId = nil;
        }

        NSString *icon = _dataList[indexPath.row][@"commodity"][@"icon"];
        NSString *name = _dataList[indexPath.row][@"commodity"][@"name"];
        NSString *goodDiscount = _dataList[indexPath.row][@"commodity"][@"commodityPrice"][@"discount"];
        NSString *goodPrice = _dataList[indexPath.row][@"commodity"][@"commodityPrice"][@"price"];
        CGFloat discount = [goodDiscount floatValue];
        CGFloat price = [goodPrice floatValue];
        NSString *commodityId = _dataList[indexPath.row][@"commodity"][@"commodityId"];
        
        
        NSUInteger goodNum = 1;
        CGFloat actualPrice = discount * price;
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setPositiveFormat:@"0.00"];
        NSString *temp = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:actualPrice]];
        CGFloat totalPrice = [temp floatValue];
        
        NSDictionary *dic = @{@"commodityId" : commodityId,
                              @"num" : @(goodNum),
                              @"storeName" : storeName,
                              @"storeId" : storeId,
                              @"couponId" : [NSNull null],
                              @"icon" : icon,
                              @"name" : name,
                              @"price" : @(totalPrice)};
        
        NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSArray *payList = @[@[resultDic]];
        
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
        BDNavigationController *nav_vc = [stroyboard instantiateViewControllerWithIdentifier:@"navPayStoryboardID"];
        BDBeidouPayViewController *vc = (BDBeidouPayViewController *)nav_vc.topViewController;
        vc.payList = payList;
        vc.isConveniency = flag;// 是否是便民商品
        [self presentViewController:nav_vc animated:YES completion:nil];
    }
}

- (IBAction)closeBuyPopViewButtonPressed:(UIButton *)sender {
    _buyPopView.hidden = YES;
}


- (IBAction)originalPurchaseButtonPressed:(UIButton *)sender {
    if (_selectedIndexPath) {
        NSIndexPath *indexPath = _selectedIndexPath;
        
        BOOL flag = NO;
        // 是否是便民商品
        NSDictionary *classify = _dataList[indexPath.row][@"commodity"][@"classify"];
        if (![classify isEqual:[NSNull null]] &&
            [classify isKindOfClass:[NSDictionary class]]) {
            NSString *firstLevel = classify[@"firstLevel"];
            if (![firstLevel isEqual:[NSNull null]]) {
                if ([firstLevel isEqualToString:@"conveniency"]) {
                    flag = YES;
                }
            }
        }
        
        NSString *storeName = _dataList[indexPath.row][@"commodity"][@"store"][@"name"];
        if ([storeName isEqual:[NSNull null]]) {
            storeName = @"某店铺";
        }
        NSString *storeId = _dataList[indexPath.row][@"commodity"][@"store"][@"storeId"];
        if ([storeId isEqual:[NSNull null]]) {
            storeId = nil;
        }
        
        NSString *icon = _dataList[indexPath.row][@"commodity"][@"icon"];
        NSString *name = _dataList[indexPath.row][@"commodity"][@"name"];
        NSString *goodDiscount = _dataList[indexPath.row][@"commodity"][@"commodityPrice"][@"discount"];
        NSString *goodPrice = _dataList[indexPath.row][@"commodity"][@"commodityPrice"][@"price"];
        CGFloat discount = [goodDiscount floatValue];
        CGFloat price = [goodPrice floatValue];
        NSString *commodityId = _dataList[indexPath.row][@"commodity"][@"commodityId"];
        
        
        NSUInteger goodNum = 1;
        CGFloat actualPrice = discount * price;
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setPositiveFormat:@"0.00"];
        NSString *temp = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:actualPrice]];
        CGFloat totalPrice = [temp floatValue];
        
        NSDictionary *dic = @{@"commodityId" : commodityId,
                              @"num" : @(goodNum),
                              @"storeName" : storeName,
                              @"storeId" : storeId,
                              @"couponId" : [NSNull null],
                              @"icon" : icon,
                              @"name" : name,
                              @"price" : @(totalPrice)};
        
        NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        NSArray *payList = @[@[resultDic]];
        
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
        BDNavigationController *nav_vc = [stroyboard instantiateViewControllerWithIdentifier:@"navPayStoryboardID"];
        BDBeidouPayViewController *vc = (BDBeidouPayViewController *)nav_vc.topViewController;
        vc.payList = payList;
        vc.isConveniency = flag;// 是否是便民商品
        [self presentViewController:nav_vc animated:YES completion:nil];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
